# backend/repositories/user_permission_repo.py

from sqlalchemy.orm import Session
from app.models.coop_app.user_permission import UserPermission
from app.models.coop_app.permission import Permission
from typing import List, Optional



def get_permission_ids_by_user_id(db: Session, user_id: str) -> List[int]:
    return [
        up.permission_id
        for up in db.query(UserPermission)
        .filter(UserPermission.user_id == user_id)
        .all()
    ]



def add_permission_to_user(db: Session, user_id: str, permission_id: int) -> None:
    existing = (
        db.query(UserPermission)
        .filter(
            UserPermission.user_id == user_id,
            UserPermission.permission_id == permission_id
        )
        .first()
    )
    if not existing:
        db.add(UserPermission(user_id=user_id, permission_id=permission_id))
        db.commit()



def remove_permission_from_user(db: Session, user_id: str, permission_id: int) -> None:
    existing = (
        db.query(UserPermission)
        .filter(
            UserPermission.user_id == user_id,
            UserPermission.permission_id == permission_id
        )
        .first()
    )
    if existing:
        db.delete(existing)
        db.commit()



def set_user_permissions(db: Session, user_id: str, new_permission_ids: List[int]) -> None:
    db.query(UserPermission).filter(UserPermission.user_id == user_id).delete()
    for pid in new_permission_ids:
        db.add(UserPermission(user_id=user_id, permission_id=pid))
    db.commit()



def user_has_permission(db: Session, user_id: str, permission_id: int) -> bool:
    return (
        db.query(UserPermission)
        .filter(
            UserPermission.user_id == user_id,
            UserPermission.permission_id == permission_id
        )
        .first()
        is not None
    )

